﻿using System;
using System.Collections.Generic;
using System.Text;

namespace DbFrame.Test.Class
{
    using System.Linq;
    using System.Collections.Concurrent;

    /// <summary>
    /// 游戏 数据 缓存 操作类
    /// </summary>
    public class ProgramCache
    {

        private static ConcurrentDictionary<string, object> _ConcurrentDictionary = new ConcurrentDictionary<string, object>();

        /// <summary>
        /// 根据Key 获取 游戏树
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static T Get<T>(string Key)
        {
            object _Value = default(T);

            if (_ConcurrentDictionary.ContainsKey(Key))
            {
                var res = _ConcurrentDictionary.TryGetValue(Key, out _Value);
            }

            return (T)_Value;
        }

        /// <summary>
        /// 获取 所有的 游戏树
        /// </summary>
        /// <returns></returns>
        public static ConcurrentDictionary<string, object> GetAll()
        {
            return _ConcurrentDictionary;
        }

        /// <summary>
        /// 根据Key 移除 游戏树
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static bool Remove(string Key)
        {
            object _Value = null;
            return _ConcurrentDictionary.TryRemove(Key, out _Value);
        }

        /// <summary>
        /// 清除所有 游戏树
        /// </summary>
        public static void Clear()
        {
            _ConcurrentDictionary.Clear();
        }

        /// <summary>
        /// 添加游戏树
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Key"></param>
        /// <param name="Data"></param>
        public static bool Add<T>(string Key, T Data)
        {
            return _ConcurrentDictionary.TryAdd(Key, Data);
        }

        /// <summary>
        /// 更新游戏树
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Key"></param>
        /// <param name="Data"></param>
        /// <returns></returns>
        public static bool Update<T>(string Key, T Data)
        {
            return _ConcurrentDictionary.TryUpdate(Key, Data, Get<T>(Key));
        }

        /// <summary>
        /// 添加或者更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Key"></param>
        /// <param name="Data"></param>
        /// <returns></returns>
        public static bool AddOrUpdate<T>(string Key, T Data)
        {
            if (_ConcurrentDictionary.ContainsKey(Key))
                return Update<T>(Key, Data);
            return Add<T>(Key, Data);
                
        }


    }
}
